/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// Copyright (c) 1996-2013 Live Networks, Inc.  All rights reserved.
// Basic Usage Environment: for a simple, non-scripted, console application
// C++ header

#ifndef _HANDLER_SET_HH
#define _HANDLER_SET_HH

#ifndef _BOOLEAN_HH
#include "Boolean.hh"
#endif

////////// HandlerSet (etc.) definition //////////
//记录socket信息，这是一个双链表的节点
class HandlerDescriptor {
  HandlerDescriptor(HandlerDescriptor* nextHandler);
  virtual ~HandlerDescriptor();

public:
  //以下的值就是 TaskScheduler::setBackgroundHandling过程中的参数
  //socket时返回的描述符
  int socketNum;
  //设置条件，例如：像SOCKET的SOCKET_READABLE|SOCKET_EXCEPTION，这个看自己的setBackgroundHandling具体实现了
  int conditionSet;
  TaskScheduler::BackgroundHandlerProc* handlerProc;
  void* clientData;

private:
  // Descriptors are linked together in a doubly-linked list:
  friend class HandlerSet;
  friend class HandlerIterator;
  //前驱
  HandlerDescriptor* fNextHandler;
  //后继
  HandlerDescriptor* fPrevHandler;
};

//这是一个SOCKET的双向循环链表
class HandlerSet {
public:
  HandlerSet();
  virtual ~HandlerSet();
  //创建一个节点，同时把它加到了末尾，如果这个文件描述符是存在了，更新其数据
  void assignHandler(int socketNum, int conditionSet, TaskScheduler::BackgroundHandlerProc* handlerProc, void* clientData);
  //清除一个节点，通过文件描述符
  void clearHandler(int socketNum);
  //dup一个文件文件描述符
  void moveHandler(int oldSocketNum, int newSocketNum);

private:
  //通过文件描述符查找节点
  HandlerDescriptor* lookupHandler(int socketNum);

private:
  friend class HandlerIterator;
  //这是一个头节点，最后一个节点的下一个节点也指向头节点（HandlerIterator在读NEXT下一个节点时，如果指向的是头节点，表示读到尾了）
  HandlerDescriptor fHandlers;
};

class HandlerIterator {
public:
  HandlerIterator(HandlerSet& handlerSet);
  virtual ~HandlerIterator();
  //下一个节点
  HandlerDescriptor* next(); // returns NULL if none
  void reset();  //重至fNextPtr，使其指向头节点的下一个节点

private:
  HandlerSet& fOurSet;         //指向双链表，这个值在创建时指定，之后不再更改，所以这里用引用
  HandlerDescriptor* fNextPtr; //记录下一个读取的节点
};

#endif
